<script setup>
import {
  Plus,
  Search
} from '@element-plus/icons-vue'
import { onMounted, ref } from 'vue'
import { ElMessage } from "element-plus";
import {addComplaintHandling, getAllComplaints, updateComplaints} from "@/api/complaint.js";
import { useTokenStore } from "@/stores/token.js";

//token
const tokenStore = useTokenStore();

//投诉列表数据
const complaints = ref([
  {
    complaintId: 1,
    touristId: 123,
    complaintContent: '这里是投诉内容。',
    resultContent: '这里是处理结果。',
    complaintPhoto: 'https://example.com/photo.jpg',
    complaintVideo: 'https://example.com/video.mp4',
    isApproved: 0,
    isProcessed: 0
  }
])
//投诉Model
const complaintModel = ref({
  complaintId: 1,
  touristId: 123,
  complaintContent: '',
  resultContent: '',
  complaintPhoto: '',
  complaintVideo: '',
  isApproved: 0,
  isProcessed: 0
})
//置空投诉Model
const resetComplaintModel = () => {
  complaintModel.value = {
    complaintId: 0,
    touristId: 0,
    complaintContent: '',
    resultContent: '',
    complaintPhoto: '',
    complaintVideo: '',
    isApproved: 0,
    isProcessed: 0
  }
}

//投诉处理模型
const handlingModel = ref({
  handlingContent: '',
  handlingPhoto: '',
  handlingVideo: '', 
  complaintId: 0,
})
//置空
const resetHandlingModel = () => {
  handlingModel.value = {
    handlingContent: '',
    handlingPhoto: '',
    complaintId: 0,
  }
}

//弹窗状态
const dialogVisible = ref(false)
//抽屉状态
const visibleDrawer = ref(false)

//搜索输入
const input = ref();
//分页条数据模型
const pageNum = ref(1)//当前页
const total = ref(20)//总条数
const pageSize = ref(3)//每页条数
//  statusFilters 包含所有可能的状态过滤器
const isApprovedFilters = ref([
  { text: '未审批', value: 0 },
  { text: '已审批', value: 1 },
]);
const isProcessedFilters = ref([
  { text: '未处理', value: 0 },
  { text: '已处理', value: 1 },
]);

// 获取所有投诉列表
const fetchComplaints = async () => {
  try {
    const result = await getAllComplaints()
    total.value = result.data.length;
    complaints.value = result.data.slice((pageNum.value - 1) * pageSize.value, pageNum.value * pageSize.value);
  } catch (error) {
    console.error('获取列表失败', error)
    ElMessage({ type: "error", message: "获取列表失败", });
  }
}

//当每页条数发生了变化，调用此函数
const onSizeChange = (size) => {
  pageSize.value = size
  fetchComplaints();
}
//当前页码发生变化，调用此函数
const onCurrentChange = (num) => {
  pageNum.value = num
  fetchComplaints();
}

//模糊搜索
const inputSearch = async () => {
  const keyword = input.value.trim(); // 转换为小写并去除首尾空格
  if (!keyword) {
    await fetchComplaints(); // 如果搜索关键词为空，则显示所有列表
    return; // 如果搜索关键词为空，直接返回，不执行后续操作
  }
  let result = await getAllComplaints(); // 获取列表
  try {
    // 根据投诉id进行模糊搜索
    total.value = result.data.data.filter(complaint =>
      complaint.complaintId.includes(keyword)
    ).length;
    complaints.value = result.data.data.filter(complaint =>
      complaint.complaintId.includes(keyword)
    );
  } catch (error) {
    console.error('搜索投诉时出错：', error);
    ElMessage.error(result.statusText || '搜索投诉时出错：');
  }
  input.value = ''; // 清空输入框
};

const filterTag = (value, row) => {
  return row.isApproved === value || row.isProcessed === value;
};

const handleRowDblClick = (row) => {
  complaintModel.value = row;
  dialogVisible.value = true;
};
const closeDialog = () => {
  resetComplaintModel();
  dialogVisible.value = false;
};

const approveComplaint = async (row) => {
  if (tokenStore.getAuth() !== 1) {
    ElMessage.error('你没有权限进行审批操作');
    return;
  }
  // 处理审批逻辑
  try {
    row.isApproved = 1;
    let result = await updateComplaints(row);
    ElMessage.success(result.message || '搜索投诉时出错：');
    dialogVisible.value = false;
    resetComplaintModel();
    await fetchComplaints();
  } catch (error) {
    console.error('审批投诉失败', error)
    ElMessage({ type: "error", message: "审批投诉失败", });
  }
};

// 处理投诉
const handleComplaint = (row) => {
  if (tokenStore.getAuth() !== 2) {
    ElMessage.error('你没有权限进行处理操作');
    return;
  }
  
  complaintModel.value = row;
  handlingModel.value.complaintId = row.complaintId;
  visibleDrawer.value = true;

};
const submitComplaint = async () => {
  if (tokenStore.getAuth() !== 2) {
    ElMessage.error('你没有权限进行处理操作');
    return;
  }
  // 提交处理结果
  try {
    await addComplaintHandling(handlingModel.value);
    // if (complaintModel.value.isApproved === 1) {
    complaintModel.value.isProcessed = 1;
    console.log(handlingModel)
    console.log(handlingModel.value)
    let result = await updateComplaints(complaintModel.value);
    ElMessage.success(result.message || '处理结果提交成功');
    // }else {
    //   ElMessage.error('投诉未审批，无法处理');
    // }
    visibleDrawer.value = false;
    resetComplaintModel();
    await fetchComplaints();
  } catch (error) {
    console.error('处理结果提交失败', error)
    ElMessage({ type: "error", message: "处理结果提交失败", });
  }
};
const cancel = () => {
  resetComplaintModel();
  visibleDrawer.value = false;
};
//上传成功,回调函数
const uploadImageSuccess = (response, file, fileList) => {
  if (response || response.status === 200) {
    // 检查服务端返回的数据结构，确认是否有 fileUrl 字段
    console.log(response);

    const fileUrl = response;
    console.log(fileUrl);

    if (fileUrl) {
      // 更新 用于显示上传的图片预览
      handlingModel.value.handlingPhoto = fileUrl;
      ElMessage.success('文件上传成功');
    } else {
      ElMessage.error('文件上传失败：未找到文件路径');
    }
  } else {
    ElMessage.error('文件上传失败');
    console.log(response);
    console.log(response.data);
  }
};
const uploadVideoSuccess = (response, file, fileList) => {
  if (response || response.status === 200) {
    // 检查服务端返回的数据结构，确认是否有 fileUrl 字段
    console.log(response);

    const fileUrl = response;
    console.log(fileUrl);

    if (fileUrl) {
      // 更新 用于显示上传的视频预览
      handlingModel.value.handlingVideo = fileUrl;
      ElMessage.success('文件上传成功');
    } else {
      ElMessage.error('文件上传失败：未找到文件路径');
    }
  } else {
    ElMessage.error('文件上传失败');
    console.log(response);
    console.log(response.data);
  }
};

onMounted(() => {
  fetchComplaints();
})
</script>
<template>
  <el-card class="page-container">
    <template #header>
      <div class="header">
        <span>投诉管理</span>
      </div>
    </template>

    <!-- 搜索表单 -->
    <el-form inline>
      <el-form-item>
        <el-input v-model="input" style="width: 240px" placeholder="请输入投诉ID" clearabl :prefix-icon="Search" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="inputSearch">搜索</el-button>
      </el-form-item>
    </el-form>

    <!-- 投诉列表 -->
    <el-table ref="multipleTableRef" :data="complaints" style="width: 100%" @row-dblclick="handleRowDblClick">
      <el-table-column type="selection" width="55" />
      <el-table-column label="投诉ID" prop="complaintId" width="60" />
      <el-table-column label="用户ID" width="400" prop="touristId"></el-table-column>
      <el-table-column label="投诉内容" prop="complaintContent"></el-table-column>
      <el-table-column prop="isApproved" label="审批状态" width="100" :filters="isApprovedFilters"
        :filter-method="filterTag" filter-placement="bottom-end">
        <template #default="scope">
          <el-tag :type="scope.row.isApproved ? 'success' : 'info'" disable-transitions>
            {{ scope.row.isApproved ? '已审批' : '未审批' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="isProcessed" label="处理状态" width="100" :filters="isProcessedFilters"
        :filter-method="filterTag" filter-placement="bottom-end">
        <template #default="scope">
          <el-tag :type="scope.row.isProcessed ? 'success' : 'info'" disable-transitions>
            {{ scope.row.isProcessed ? '已处理' : '未处理' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200">
        <template #default="{ row }">
          <el-button circle plain type="primary" @click="approveComplaint(row)">审批</el-button>
          <el-button circle plain type="primary" @click="handleComplaint(row)">处理</el-button>
        </template>
      </el-table-column>
      <template #empty>
        <el-empty description="暂无数据" />
      </template>
    </el-table>

    <!-- 投诉详情弹窗 -->
    <el-dialog title="投诉详情" v-model="dialogVisible">
      <el-form label-width="120px">
        <el-form-item label="投诉 ID">
          <el-input v-model="complaintModel.complaintId" disabled></el-input>
        </el-form-item>
        <el-form-item label="游客 ID">
          <el-input v-model="complaintModel.touristId" disabled></el-input>
        </el-form-item>
        <el-form-item label="投诉内容">
          <el-input v-model="complaintModel.complaintContent" disabled></el-input>
        </el-form-item>
        <el-form-item label="处理结果">
          <el-input v-model="complaintModel.resultContent" disabled></el-input>
        </el-form-item>
        <el-form-item label="投诉照片">
          <el-image :src="complaintModel.complaintPhoto" fit="cover"></el-image>
        </el-form-item>
        <el-form-item label="投诉视频">
          <video width="320" height="240" controls>
            <source :src="complaintModel.complaintVideo" type="video/mp4">
            Your browser does not support the video tag.
          </video>
        </el-form-item>
        <el-form-item label="审批状态">
          <el-tag :type="complaintModel.isApproved === 1 ? 'success' : 'info'">
            {{ complaintModel.isApproved === 1 ? '已审批' : '未审批' }}
          </el-tag>
        </el-form-item>
        <el-form-item label="处理状态">
          <el-tag :type="complaintModel.isProcessed === 1 ? 'success' : 'info'">
            {{ complaintModel.isProcessed === 1 ? '已处理' : '未处理' }}
          </el-tag>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeDialog">关闭</el-button>
      </div>
    </el-dialog>

    <!-- 抽屉 -->
    <el-drawer title="处理投诉" v-model="visibleDrawer" width="300px" direction="rtl">
      <el-form ref="complaintForm" :model="handlingModel" label-width="80px">
        <el-form-item label="处理结果">
          <el-input v-model="handlingModel.handlingContent"></el-input>
        </el-form-item>
        <el-form-item label="处理照片">
          <el-upload class="avatar-uploader" :auto-upload="true" :show-file-list="false" action="/api/fileUpload"
            name="file" :headers="{ 'Authorization': tokenStore.token }" :on-success="uploadImageSuccess">
            <img v-if="handlingModel.handlingPhoto" :src="handlingModel.handlingPhoto" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="处理视频">
          <el-upload class="video-uploader" :auto-upload="true" :show-file-list="false" action="/api/fileUpload"
            name="file" :headers="{ 'Authorization': tokenStore.token }" :on-success="uploadVideoSuccess">
            <video v-if="handlingModel.handlingVideo" :src="handlingModel.handlingVideo" class="video" controls />
            <el-icon v-else class="video-uploader-icon">
              <Plus />
            </el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="处理状态">
          <el-input v-model="handlingModel.isProcessed" type="number" disabled></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div style="text-align: right;">
          <el-button @click="cancel">取消</el-button>
          <el-button type="primary" @click="submitComplaint">提交</el-button>
        </div>
      </template>
    </el-drawer>

    <!-- 分页条 -->
    <el-pagination v-model:current-page="pageNum" v-model:page-size="pageSize" :page-sizes="[3, 5, 10, 15]"
      layout="jumper, total, sizes, prev, pager, next" background :total="total" @size-change="onSizeChange"
      @current-change="onCurrentChange" style="margin-top: 20px;
        justify-content: flex-end" />
  </el-card>
</template>
<style scoped>
.page-container {
  min-height: 100%;
  box-sizing: border-box;

  .header {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
}
</style>